using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ctsu.Data;


namespace ctsu.Admin.Forms
{
	public class NewListRecordDlg : System.Windows.Forms.Form
	{
		public string NewItem;
		public int NewID;
		private string _fieldName;
		private string _tableName;
		private DataTable _tableSchema;

		private System.Windows.Forms.Button btnCancel;
		private System.Windows.Forms.Button btnSave;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox Item;

		private System.ComponentModel.Container components = null;

		public NewListRecordDlg(string field, string table, DataTable tableSchema)
		{
			InitializeComponent();
			this._fieldName = field;
			this._tableName = table;
			this._tableSchema = tableSchema;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnCancel = new System.Windows.Forms.Button();
			this.btnSave = new System.Windows.Forms.Button();
			this.Item = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(171, 56);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.TabIndex = 9;
			this.btnCancel.Text = "&Cancel";
			this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
			// 
			// btnSave
			// 
			this.btnSave.Location = new System.Drawing.Point(83, 56);
			this.btnSave.Name = "btnSave";
			this.btnSave.TabIndex = 8;
			this.btnSave.Text = "&Save";
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			// 
			// Item
			// 
			this.Item.Location = new System.Drawing.Point(80, 16);
			this.Item.Name = "Item";
			this.Item.Size = new System.Drawing.Size(240, 20);
			this.Item.TabIndex = 0;
			this.Item.Text = "";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(72, 16);
			this.label1.TabIndex = 10;
			this.label1.Text = "New list item:";
			// 
			// NewListRecordDlg
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.btnCancel;
			this.ClientSize = new System.Drawing.Size(328, 86);
			this.Controls.Add(this.Item);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnSave);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.Name = "NewListRecordDlg";
			this.Text = "NewListRecordDlg";
			this.Load += new System.EventHandler(this.NewListRecordDlg_Load);
			this.ResumeLayout(false);

		}
		#endregion

		private void NewListRecordDlg_Load(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			DataColumn dc = this._tableSchema.Columns[this._fieldName];
			this.Item.MaxLength = dc.MaxLength;

			this.Text = "New List Item - Table: " + this._tableName;
			this.NewID = -1;
		}

		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void btnSave_Click(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			if (Item.Text.Trim().Length == 0)
			{
				sb.Append("Enter a new list item");
				MessageBox.Show(this, sb.ToString(), "Enter New Item Name", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				Item.Focus();
				return;
			}
			if (IsDuplicate())
				return;

			string sql = "INSERT INTO " + this._tableName +
				" (" + this._fieldName + ") " +
				" VALUES ('" + Item.Text.Trim() + "')";

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			try
			{
				DataAccess.ExecuteNonQuery(CommandType.Text, sql);
				//get the new id				
				object o = DataAccess.GetScalarObject(CommandType.Text, @"SELECT @@IDENTITY");
				if (o != null)
					this.NewID = Convert.ToInt32(o);
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not save new item.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}

			this.DialogResult = DialogResult.OK;
			this.NewItem = Item.Text;
			this.Close();
		}

		private bool IsDuplicate()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT " + this._fieldName +
				" FROM " + this._tableName +
				" WHERE " + this._fieldName + "='" + this.Item.Text + "'";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader dr = null;
			try
			{
				dr = DataAccess.GetDataReader(sql);

				if (dr.Read())
				{
					MessageBox.Show(this, "This item already exits in the table.", "Duplicate Item", MessageBoxButtons.OK, MessageBoxIcon.Stop);
					Item.Focus();
					return true;
				}
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Encountered an error while checking for duplicate item.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Enter New Item Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return true;
			}
			finally
			{
				if (dr != null)
				{
					if (!dr.IsClosed)
						dr.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
			return false;
		}
	}
}
